package product

import (
	"context"

	"mall/service/backend/common/i18n"
	"mall/service/product/rpc/internal/svc"
	"mall/service/product/rpc/internal/utils/errorhandler"
	"mall/service/product/rpc/types/product"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteProductLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeleteProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteProductLogic {
	return &DeleteProductLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DeleteProductLogic) DeleteProduct(in *product.IDsReq) (*product.BaseResp, error) {
	if len(in.Ids) == 0 {
		return &product.BaseResp{}, nil
	}

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	for _, id := range in.Ids {
		if id > 0 {
			err = l.svcCtx.CurrentProduct.SoftDelete(l.ctx, tx, id)
			if err != nil {
				tx.Rollback()
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}
		}
	}

	tx.Commit()

	return &product.BaseResp{
		Msg: i18n.DeleteSuccess,
	}, nil
}
